package com.broheim.websocket.core.listener;

import com.broheim.websocket.core.event.accept.Event;
import com.broheim.websocket.core.event.accept.OnMessageEvent;
import com.broheim.websocket.core.handler.Handler;
import com.broheim.websocket.core.message.JsonMessage;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class JsonMessageListener implements Listener {

    private ObjectMapper objectMapper = new ObjectMapper();

    private Map<String, Handler> handlerMap = new HashMap<>();

    public void register(String path, Handler handler) {
        handlerMap.put(path, handler);
    }

    @Override
    public void onEvent(Event event, ListenerChain chain) throws Exception {
        if (event instanceof OnMessageEvent) {
            OnMessageEvent onMessageEvent = (OnMessageEvent) event;
            String message = onMessageEvent.getMessage();
            JsonMessage jsonMessage = objectMapper.readValue(message, JsonMessage.class);
            Handler handler = handlerMap.get(jsonMessage.getCmd());
            if (Optional.ofNullable(handler).isPresent()) {
                handler.handle(onMessageEvent.getChannelContext(), jsonMessage.getBody());
            }
        }
    }
}
